var express = require('express');
var token = require('./token.js')
var bodyParser = require('body-parser');

var app = express();

var router = express.Router();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));



router.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.use('/api/*', function (req, res, next) {
  console.log('Request URL:', req.originalUrl);
  if (req.originalUrl !== '/api/login') {
    var k = req.get('authorization')
    console.log(k, 'k')
    if (!token.checkToken(k)) {
      res.status(500).send('token error');
      return
    }
  }
  next();
});

router.post('/api/login', function (req, res) {
  if (req.body.name && req.body.pass) {
    // 验证用户名与密码省略...
    var k = token.createToken({ name: req.body.name, possword: req.body.pass }, 1200)
    var data = {
      message: '登录成功!',
      token: k
    }
    res.send(data);
  } else {
    res.status(500).send('error');
  }
});


router.get('/api/hello', function (req, res) {
  let data = { message: 'Hello word!' }
  res.send(data);
});

app.use('/', router);

var server = app.listen(8080, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('应用实例，访问地址为 http://%s:%s', host, port);
})


